package engine.scene.player
{
	import engine.GameData;
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.SceneObject;
	import engine.flag.GameDefine;
	import engine.flag.PlayerActionFlag;
	import engine.logic.login.PlayCDTimerLogic;
	import engine.logic.tips.TipsManage;
	import engine.logic.walk.Astar.ForbiddenAreaLogic;
	import engine.logic.walk.RollerMoveLogic;
	import engine.logic.walk.WalkManager;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.newUi.CurrencyResultLogic;
	import engine.newUi.FactionBossExitUI;
	import engine.newUi.FactionBossUI;
	import engine.newUi.NoticeUI;
	import engine.newUi.SnowBossBloodUI;
	import engine.newUi.WorldBossBloodUI;
	import engine.newUi.WorldBossExitUI;
	import engine.scene.SceneChangeManager;
	import engine.scene.SceneManager;
	import engine.scene.SceneView;
	import engine.ui.MainUIManager;
	import engine.ui.MsgTipsLogic;
	import engine.util.FilterUtil;
	
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.utils.setTimeout;
	
	import newx.StageInfo;
	import newx.com.config.StaticIni;
	import newx.com.control.button.NxButton;
	import newx.com.control.text.NxLabel;
	import newx.utils.debug.IO;
	
	public class RoleModel extends PlayerModel
	{
		private var _sceneView 		:SceneView;
		private var _deadTimeLabel		:NxLabel;
		private var aliveBtn			:NxButton;
		private var _worldPlayDead		:int
		private var _bindManage		:BindManage;
		private var _model				:ModelLocator;
		
		private var bindTimeIndex		:int;
		private var bindSnowTimeIndex		:int;
		
		private  var _walkPlacePoints	:Object;
		
		private var _roleModelEffect	:RoleModelEffect;
		
		private var _effectPlace		:Sprite;
		
		private var _perPoint			:Point;
		
		private var _clotheModel		:int;
		
		private var _tipLogic			:MsgTipsLogic;
		
		private var _tipPlace			:Sprite;
		
		public function RoleModel()
		{
			super();
			moveLogic.speed = 8;
			_model			=	ModelLocator.getInstance();
			_bindManage		=	BindManage.getInstance();
			_walkPlacePoints=	StaticIni.getIniObj( "WalkAreaXY" );
			_deadTimeLabel	=	new NxLabel();
			_deadTimeLabel.htmlStrByBorder	= ""
			addChild(_deadTimeLabel);
			_moveLogic 		= new RollerMoveLogic();
			initAliveBtn();
			_sceneView 		= SceneManager.getInstance().norSceneView;
			
			(_moveLogic as RollerMoveLogic).sceneModel = _sceneView;
			bindTimeIndex 	= PlayCDTimerLogic.getInstance().resgis(11,checkTime);
			bindSnowTimeIndex 	= PlayCDTimerLogic.getInstance().resgis(22,checkSnowTime);
			
			_bindManage.BindProp(_model.scene,"WorldBossState",this,"worldPlayWait");
			_bindManage.BindProp(_model.scene.Role,"GuildBanditiState",this,"worldPlayWait");
			_bindManage.BindProp(_model.scene.Role,"SnowballFightDead",this,"snowballFightDead");
			_bindManage.BindProp(_model.scene.Role,"WorldPlayerDead",this,"worldPlayDead");
			_bindManage.BindProp(_model.scene.Role,"ClotheModel",this,"clotheModel");
			_bindManage.BindProp(_model.scene.Role,"ModelEx",this,"modelEx");
			_bindManage.BindProp(_model.scene.Role,"ChallengeIndex",this,"challengeIndex");
			_bindManage.BindProp(_model.scene.Role,"FollowPetName",this,"updateFollowPetName");
			_bindManage.BindProp(_model.scene.Role,"FollowPetGrade",this,"updateFollowPetGrade");
			_bindManage.BindProp(_model.scene.Role,"FollowPetLevel",this,"updateFollowPetLevel");
			_bindManage.BindProp(_model.scene.Role,"FollowPet",this,"updateFollowPet");
			_bindManage.BindProp(_model.scene.Role,"GuildName",this,"updateGuildName");
			
			
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_FIGHT_TICK), onFightTick );
			
			_effectPlace	= new Sprite();
			addChild( _effectPlace );
			
			_roleModelEffect=	new RoleModelEffect( _effectPlace, this );
			
			_tipPlace = new Sprite();
			addChild( _tipPlace );
			_tipLogic = MsgTipsLogic.getRes(_tipPlace,0,-70,true);
		}
		
		public function set updateGuildName(val:String):void
		{
			this.setPlayerName();
		}
		
		public function get tipPlace():Sprite
		{
			return _tipPlace;
		}
		
		private function initAliveBtn():void
		{
			aliveBtn		=	new NxButton();
			aliveBtn.skin	=	"Button_3";
			aliveBtn.label	=	"";
			aliveBtn.width	=	aliveBtn.height	=	18;
			aliveBtn.buttonMode	=	true;
			addChild(aliveBtn);
			aliveBtn.visible	=	false;
			aliveBtn.addEventListener(MouseEvent.MOUSE_DOWN,onAlive);
			aliveBtn.addEventListener(MouseEvent.MOUSE_OVER,onBtnOver);
			aliveBtn.addEventListener(MouseEvent.MOUSE_OUT,onBtnOut);
		}
		public function set updateFollowPet(value:int):void
		{
			//			updataPlayerInfo(playerObj);
			followPet = String(value);
		}
		public function set updateFollowPetName(nameStr:String):void
		{
			//			updataPlayerInfo(playerObj);
			followPetName =nameStr;
		}
		public function set updateFollowPetGrade(value:int):void
		{
			followPetGrade = value;
		}
		public function set updateFollowPetLevel(value:int):void
		{
			followPetLevel = value;
		}
		public function set challengeIndex(value : int ):void
		{
			updataPlayerChange( playerObj );
		}
		
		override public function set status(value:String):void
		{
			super.status = value;
			
			if( _deadTimeLabel.text || aliveBtn.visible )
			{
				if( _challengeMc != null )
				{
					_deadTimeLabel.y	=	_challengeMc.y - _deadTimeLabel.height;
				}else
				{
					_deadTimeLabel.y	=	_familyLabel.y - _deadTimeLabel.height;
				}
				aliveBtn.y			=	_deadTimeLabel.y;
			}
		}
		
		/**
		 *	战斗冷却 
		 */		
		private function onFightTick( evt : CustomMsgEvent ):void
		{
			NoticeUI.getInstance().showInfo( evt.pList[ 0 ] + "秒才后进入战斗");
			
			resetPerPoint();
		}
		
		override protected function updataPlayerInfo( playerObj : SceneObject ):void
		{
			super.updataPlayerInfo( playerObj );
			
			setSceneViewRect();
			
			if( playerObj != null && _playerMovie != null && _playerMovie.overhead)
			{
				_tipPlace.y = _playerMovie.overhead.y;
			}
		}
		
		public function setSceneViewRect():void
		{
			if(GameData.SceneType==GameDefine.SceneType_ForbiddenAreaScene) return;
			
			var gameWidth : int = SceneChangeManager.getGameWidth();
			
			if( x < gameWidth * .5)
			{
				_sceneView.x = (StageInfo.rootW - gameWidth) * .5;
			}else
			{
				//小于左半屏幕，return
				if(x >= gameWidth * .5)
				{
					var xOffsize : int = (StageInfo.rootW * .5) - x;
					var viewOffsize : int = (gameWidth - 2500) - (gameWidth - StageInfo.rootW) * .5;
					
					if( xOffsize > viewOffsize )
					{
						_sceneView.x = xOffsize;
					}else
					{
						_sceneView.x = viewOffsize;
					}
				}
			}
		}
		
		override public function killMove():void
		{
			super.killMove();
			if(_petModel)
				_petModel.status=PlayerActionFlag.NormalWait;
			//隐藏
			_sceneView.hideWalkIocn();
			
			MainUIManager.getInstance().autoFoundWay = false;
		}
		
		//回到初始地点
		private function resetPerPoint( isRect : Boolean = true ):void
		{
			killMove();
			
			resetPoint();
			
		}
		
		//回到初始地点 优化
		public function resetPoint( isRect : Boolean = true ):void
		{
			WorldBossBloodUI.getInstance().autoAtack(false);
			
			killMove();
			
			if(GameData.SceneType == GameDefine.SceneType_WorldBossScene)				
			{
				setTimeout(function():void{WorldBossBloodUI.getInstance().autoAtack(true)},2000);
			}
			if(GameData.SceneType == GameDefine.SceneType_FactionBossScene)
			{
				setTimeout(function():void{FactionBossUI.getInstance().autoAtack(true)},2000);
			}
			
			if( GameData.SceneType == GameDefine.SceneType_WorldBossScene || GameData.SceneType	==	GameDefine.SceneType_FactionBossScene)
			{
				var rolePoint : Point = new Point();
				var standPoint : Array =  SceneManager.getInstance().walkPlacePoints[ "wait" ].split( "," );
				rolePoint.x = int( standPoint[0] ) + int( standPoint[2] * Math.random() );
				rolePoint.y = int( standPoint[1] ) + int( standPoint[3] * Math.random() );
				
				point = rolePoint;
				
				//优化 告诉服务端坐标
				SystemSender.getInstance().CustomMsg( CustomToServerFlag.CLIENT_CUSTOMMSG_PLAYER_STOP, 
					int( rolePoint.x ), int( rolePoint.y ) );
			}
			else if( GameData.SceneType == GameDefine.SceneType_ForbiddenAreaScene )
			{
				var type:int	=	CurrencyResultLogic.getInstance().type;
				if(type==4)
				{
					var pointArr:Array	=	(_model.scene.Role.GetProperties("ResetPoint") as String).split(",");
					if(pointArr.length == 1) return;
					point = new Point(pointArr[0]*20,pointArr[1]*20);
				}
				else
				{
					point = new Point(GameData.Role.x,GameData.Role.y);
				}
				//告诉服务端
				SystemSender.getInstance().CustomMsg( CustomToServerFlag.CLIENT_CUSTOMMSG_PLAYER_MOVETO, 
					x, y, int( point.x ), int( point.y ) );
			}
			else
			{
				var obj : Object = StaticIni.getIniObj("config_pos");
				
				point = new Point( obj.x, obj.y );
				//告诉服务端
				SystemSender.getInstance().CustomMsg( CustomToServerFlag.CLIENT_CUSTOMMSG_PLAYER_MOVETO, 
					x, y, int( point.x ), int( point.y ) );
			}
			
			if( isRect )
			{
				setSceneViewRect();
			}
		}
		/**
		 * 玩家的死亡状态 
		 * @param val 1:死;2:活
		 * 
		 */		
		override public function set worldPlayDead(val:int):void
		{
			try
			{
				var sceneType : int = GameData.SceneType
			}
			catch(e:Error)
			{
				IO.traceError("GameData 尚未初始化");
				return;
			}
			
			if( sceneType != GameDefine.SceneType_WorldBossScene && sceneType !=GameDefine.SceneType_FactionBossScene )
			{
				return;
			}
			if(_model.scene.GetPropertiesEx( "WorldBossState" )==1) return;
			
			if( sceneType == GameDefine.SceneType_WorldBossScene)
			{
				if(val == 1)
				{
					SceneManager.getInstance().isDeadWay	=	true;
//					if(WorldBossBloodUI.getInstance().isAutoAttack) resetPerPoint();
				}
				else
				{
					SceneManager.getInstance().isDeadWay	=	false;
					_deadTimeLabel.htmlStrByBorder	=	"";
					aliveBtn.visible	=	false;
					WorldBossBloodUI.getInstance().autoAtack(true);
				}
			}
			if( sceneType == GameDefine.SceneType_FactionBossScene)
			{
				if(val == 1)
				{
					SceneManager.getInstance().isDeadWay	=	true;
//					if(FactionBossUI.getInstance().isAutoAttack) resetPerPoint();
				}
				else
				{
					SceneManager.getInstance().isDeadWay	=	false;
					_deadTimeLabel.htmlStrByBorder	=	"";
					aliveBtn.visible	=	false;
					WorldBossBloodUI.getInstance().autoAtack(true);
				}
			}
			
			super.worldPlayDead = val;
			
		}
		
		/**
		 * 角色等待状态区域限制
		 * 0 关闭
		 * 1 准备
		 * 2 开启
		 * 3 非剿匪场景(特殊处理@宾总||顾凡)
		 * @param val
		 */		
		public function set worldPlayWait(val:int):void
		{
			if(val	==	3) return;
			var walkPoint:String = "";
			if(val == 1)
			{
				walkPoint = _walkPlacePoints[ "wait" ];
				WalkManager.getInstance().findWayLogic.updaWalkPlace( walkPoint.split( "," ) );
			}
			else
			{
				walkPoint = _walkPlacePoints[ "12330100" ];
				WalkManager.getInstance().findWayLogic.updaWalkPlace( walkPoint.split( "," ) );
			}
		}
		
		public function set snowballFightDead(val:int):void
		{
			if(val == 1)
			{
				super.worldPlayDead	=	1;
			}
			else
			{
				super.worldPlayDead	=	0;
			}
		}
		/**
		 * 换装 
		 * @param val
		 * 
		 */		
		public function set clotheModel(val:int):void
		{
			_clotheModel	=	val;
			
			_clotheModel	=	_clotheModel<1 ? 1 : _clotheModel;
//trace("_________________________________"+_model.scene.Role.GetPropertiesEx("ClotheModel"))
			upDataPlayModel(_model.scene.Role);
		}
		public function set modelEx(val:int):void
		{
			upDataPlayModel(_model.scene.Role);
		}
		/**
		 * 计时器函数
		 */		
		private function checkTime(val:int,col:int):void
		{
			if( (GameData.SceneType != GameDefine.SceneType_WorldBossScene && GameData.SceneType != GameDefine.SceneType_FactionBossScene) || 
				_model.scene.GetProperties("WorldBossState") == 1 || _model.scene.Role.GetProperties("GuildBanditiState") == 1 ||
				FactionBossExitUI.getInstance().worldBossState	==	1 || WorldBossExitUI.getInstance().worldBossState == 1)
			{
				_deadTimeLabel.htmlStrByBorder	=	"";
				aliveBtn.visible	=	false;
				if(GameData.SceneType == GameDefine.SceneType_FactionScene) return;
				_playerPlace.filters = null;
				return;
			}
			if(val <= 0)
			{
				if( _model.scene.Role.GetProperties("WorldPlayerDead") == 1 )
				{
					return;
				}
				if(GameData.SceneType == GameDefine.SceneType_WorldBossScene)
				{
					if(WorldBossBloodUI.getInstance().isDead == true)
					{
						WorldBossBloodUI.getInstance().isDead = false;
					}
				}
				else
				{
					if(FactionBossUI.getInstance().isDead == true)
					{
						FactionBossUI.getInstance().isDead = false;
					}
				}
				_deadTimeLabel.htmlStrByBorder	=	"";
				aliveBtn.visible	=	false;
			}
			else
			{
				if( _model.scene.Role.GetProperties("WorldPlayerDead") != 1 ) return;
				if(GameData.SceneType == GameDefine.SceneType_WorldBossScene)
				{
					if(WorldBossBloodUI.getInstance().isDead == false)
					{
						WorldBossBloodUI.getInstance().isDead = true;
						worldPlayDead = 1;
					}
				}
				else
				{
					if(FactionBossUI.getInstance().isDead == false)
					{
						FactionBossUI.getInstance().isDead = true;
						worldPlayDead = 1;
					}
				}
				_playerPlace.filters = [FilterUtil.GrayColorFilter];
				_deadTimeLabel.htmlStrByBorder = PlayCDTimerLogic.getInstance().getTimerStr(val,false);
				if(_playerMovie!=null)
				{
					if( _challengeMc != null )
					{
						_deadTimeLabel.y	=	_challengeMc.y - _deadTimeLabel.height;
					}else
					{
						_deadTimeLabel.y	=	_familyLabel.y - _deadTimeLabel.height;
					}
					
					_deadTimeLabel.x	=	_playerMovie.overhead.x - _deadTimeLabel.width * .5;
				}
				aliveBtn.visible	=	true;
				aliveBtn.y			=	_deadTimeLabel.y;
				aliveBtn.x			=	_deadTimeLabel.x	+	_deadTimeLabel.width + 5;
			}
		}
		
		private function checkSnowTime(val:int,col:int):void
		{
			if( GameData.SceneType != GameDefine.SceneType_SnowBallFightScene && 
				GameData.SceneType != GameDefine.SceneType_WorldBossScene &&
				GameData.SceneType != GameDefine.SceneType_FactionBossScene )
			{
				_deadTimeLabel.htmlStrByBorder	=	"";
				aliveBtn.visible	=	false;
				if(GameData.SceneType == GameDefine.SceneType_FactionScene) return;
				_playerPlace.filters = null;
				return;
			}
			if(GameData.SceneType != GameDefine.SceneType_SnowBallFightScene) return;
			if(val <= 0)
			{
				if( _model.scene.Role.GetProperties("SnowballFightDead") == 1 )
				{
					return;
				}
				if(SnowBossBloodUI.getInstance().isDead == true)
				{
					SnowBossBloodUI.getInstance().isDead = false;
				}
				_deadTimeLabel.htmlStrByBorder	=	"";
			}
			else
			{
				if( _model.scene.Role.GetProperties("SnowballFightDead") != 1 ) return;
				if(SnowBossBloodUI.getInstance().isDead == false)
				{
					SnowBossBloodUI.getInstance().isDead == true
					super.worldPlayDead = 1;
				}
				_deadTimeLabel.htmlStrByBorder = PlayCDTimerLogic.getInstance().getTimerStr(val,false);
				if(_playerMovie!=null)
				{
					if( _challengeMc != null )
					{
						_deadTimeLabel.y	=	_challengeMc.y - _deadTimeLabel.height;
					}else
					{
						_deadTimeLabel.y	=	_familyLabel.y - _deadTimeLabel.height;
					}
					
					_deadTimeLabel.x	=	_playerMovie.overhead.x - _deadTimeLabel.width * .5;
				}
			}
		}
		
		private function onAlive(e:MouseEvent):void
		{
			e.stopImmediatePropagation();
			GameData.SceneType == GameDefine.SceneType_WorldBossScene?WorldBossBloodUI.getInstance().funcBtn2.dispatchEvent(new MouseEvent(MouseEvent.CLICK)):FactionBossUI.getInstance().funcBtn2.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
		}
		
		private function onBtnOver(e:MouseEvent):void
		{
			TipsManage.showTips(StaticIni.getSwfLangStr("UIString_1000195"));
		}
		
		private function onBtnOut(e:MouseEvent):void
		{
			TipsManage.hideTips();
		}
		
		override public function startMove( path : Array, callBackFunc : Function = null, pList : * = null ):void
		{
			if( Point.distance( point, path[ 0 ] ) < 20 )return;
			
			_perPoint = point;
//[ WalkManager.getInstance().findWayLogic.getWalkNode( path[ 0 ] ) ]
			
			if( (GameData.SceneType == GameDefine.SceneType_WorldBossScene || 
				GameData.SceneType == GameDefine.SceneType_FactionBossScene )&&
				_model.scene.Role.GetProperties("WorldPlayerDead")==1 &&
				! WalkManager.getInstance().findWayLogic.RoleWalkRect.contains( path[0].x-1,path[0].y+1 )
			)
			{
//				GameData.Role.killMove();
				return;
			}
			super.startMove( path, callBackFunc, pList );
		}
		
		public function getOverheadPoint():Point
		{
			return new Point( _playerMovie.overhead.x, _playerMovie.overhead.y );
		}
		
		public function get tipLogic():MsgTipsLogic
		{
			return _tipLogic;
		}
		
		override protected function getPosPoint(playerObj:SceneObject):Point
		{
			if(GameData.SceneType == GameDefine.SceneType_ForbiddenAreaScene )
			{
				var pointStr:String	=	StaticIni.getIniVar("EnterPoint_"+GameData.SceneConfig,"point");
				if(pointStr!="")
				{
					var pointArr:Array	=	pointStr.split(",");
					var cellSize:int	=	ForbiddenAreaLogic.getInstance()._cellSize;
					point	=	new Point(int(pointArr[0])*cellSize,int(pointArr[1])*cellSize);
					return point;
				}
			}
			return super.getPosPoint(playerObj);
		}
		
	}
}